package com.nowcoder.community.controller;

import com.nowcoder.community.annotation.LoginRequired;
import com.nowcoder.community.entity.Comment;
import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.entity.Page;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.*;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.HostHolder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController implements CommunityConstant {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Value("${community.path.upload}")
    private String uploadPath;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private LikeService likeService;

    @Autowired
    private FollowService followService;

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private CommentService commentService;

    /**
     * 设置个人页面
     * 此处做云存储处理时
     * 构造上传文件名，设置相应信息，生成上传凭证
     * 以上数据返回页面
     * @return
     */
    @LoginRequired
    @RequestMapping(path = "/setting",method = RequestMethod.GET)
    public String getSettingPage(){
        return "/site/setting";
    }

    /**
     * 更换云存储后需要更新存储路径的方法
     * 文件名+服务器访问路径
     * 修改数据库路径
     */

    /**
     * 上传头像
     * 此处做云存储处理可废弃
     * @param headerImage
     * @param model
     * @return
     */
    @LoginRequired
    @RequestMapping(path = "/upload",method = RequestMethod.POST)
    public String uploadHeader(MultipartFile headerImage, Model model){
        if(headerImage==null){
            model.addAttribute("error","没有上传图片!");
            return "/site/setting";
        }
//        获取用户原始文件名
        String fileName =  headerImage.getOriginalFilename();
//        获取用户文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf('.')+1);
        if (StringUtils.isBlank(suffix)){
            model.addAttribute("error","文件的格式不正确");
            return "/site/setting";
        }

//        生成随机文件名
        fileName = CommunityUtil.generateUUID() + suffix;
//        确定文件存放的路径
        File dest = new File(uploadPath+"/"+fileName);
        try {
//            存储到文件路径
            headerImage.transferTo(dest);
        } catch (IOException e) {
            logger.error("上传文件失败:",e.getMessage());
            throw new RuntimeException("上传文件失败,服务器发生异常!",e);
        }

//        更新当前头像路径
//        http://localhost:8080/community/user/header/xxx.png
        User user = hostHolder.getUser();
        String headerUrl = domain+contextPath+"/user/header/"+fileName;
        userService.updateHeader(user.getId(),headerUrl);

        return "redirect:/index";
    }


    /**
     * 获取用户头像
     * 此处做云存储处理后可废弃
     * @param fileName
     * @param response
     */
    @RequestMapping(path = "/header/{fileName}",method = RequestMethod.GET)
    public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response){
//        服务器存放路径
        fileName =uploadPath+"/"+fileName;
//        提取后缀
        String suffix = fileName.substring(fileName.lastIndexOf('.')+1);
//        响应图片
        response.setContentType("image/"+suffix);
        try(
                FileInputStream fis = new FileInputStream(fileName);
                OutputStream os = response.getOutputStream();
        ) {
            byte[] buffer = new byte[1024];
            int b = 0;
            while((b = fis.read(buffer))!=-1){
                os.write(buffer,0,b);
            }
        } catch (IOException e) {
            logger.error("图像加载失败!",e.getMessage());
        }
    }

    /**
     * 修改密码
      */
    @RequestMapping(path = "/setPassword",method = RequestMethod.POST)
    public String setPassword(String oldPassword,String newPassword,String rePassword,Model model){
        Map<String,Object> map = userService.setPassword(hostHolder.getUser().getId(),oldPassword,newPassword,rePassword);
        if (map==null || map.isEmpty()){
            model.addAttribute("msg","密码修改成功");
            model.addAttribute("target","/index");
            return "/site/operate-result";
        }else{
            model.addAttribute("oldPasswordMsg",map.get("oldPasswordMsg"));
            model.addAttribute("newPasswordMsg",map.get("newPasswordMsg"));
            model.addAttribute("rePasswordMsg",map.get("rePasswordMsg"));
            return "/site/setting";
        }
    }

    /**
     * 访问个人主页
     * @param userId
     * @param model
     * @return
     */
    @RequestMapping(path = "/profile/{userId}",method = RequestMethod.GET)
    public String getProfilePage(@PathVariable("userId") int userId,Model model){
        User user = userService.findUserById(userId);
        if(user==null){
            throw new RuntimeException("该用户不存在!");
        }
        //用户
        model.addAttribute("user",user);
        //点赞数量
        int likeCount = likeService.findUserLikeCount(userId);
        model.addAttribute("likeCount",likeCount);
        // 关注数
        long followeeCount = followService.findFolloweeCount(userId,ENTITY_TYPE_USER);
        model.addAttribute("followeeCount",followeeCount);
        // 粉丝数
        long followerCount = followService.findFollowerCount(ENTITY_TYPE_USER,userId);
        model.addAttribute("followerCount",followerCount);
        // 点赞状态
        Boolean hasFollowed = false;

        if(hostHolder.getUser()!=null){
            hasFollowed = followService.hasFollowed(hostHolder.getUser().getId(),ENTITY_TYPE_USER,userId);
        }
        model.addAttribute("hasFollowed",hasFollowed);
        return "/site/profile";
    }

    /**
     * 个人的帖子
     */
    @RequestMapping(path = "/mypost/{userId}",method = RequestMethod.GET)
    public String getMyPost(@PathVariable("userId") int userId, Page page, Model model){
        User user = userService.findUserById(userId);
        if(user==null){
            throw new RuntimeException("该用户不存在");
        }
        model.addAttribute("user",user);

        //分页信息
        page.setPath("/user/mypost/"+userId);
        page.setRows(discussPostService.findDiscussPostRows(userId));

        //帖子列表//用户界面按照创建时间排序
        List<DiscussPost> discussPostList = discussPostService.findDiscussPosts(userId, page.getOffset(), page.getLimit(),0);
        List<Map<String,Object>> discussVOList = new ArrayList<>();
        if(discussPostList!=null){
            for(DiscussPost post:discussPostList){
                Map<String,Object> map = new HashMap<>();
                map.put("post",post);
                map.put("likeCount",likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId()));
                discussVOList.add(map);
            }
        }

        model.addAttribute("discussPosts",discussVOList);
        return "/site/my-post";

    }

    /**
     * 个人的评论/回复
     * @param userId
     * @param page
     * @param model
     * @return
     */
    @RequestMapping(path = "/myreply/{userId}",method = RequestMethod.GET)
    public String getMyReply(@PathVariable("userId") int userId,Page page,Model model){
        User user = userService.findUserById(userId);
        if(user==null){
            throw new RuntimeException("该用户不存在");
        }
        model.addAttribute("user",user);

        //分页信息
        page.setPath("/user/myreply/"+userId);
        page.setRows(commentService.findCommentCountByUser(userId));

        List<Comment> commentList = commentService.findCommentsByUser(userId,page.getOffset(),page.getLimit());
        List<Map<String,Object>> commentVOList = new ArrayList<>();
        if(commentList!=null){
            for(Comment comment:commentList){
                Map<String,Object> map = new HashMap<>();
                map.put("comment",comment);
                DiscussPost post = discussPostService.findDiscussPostById(comment.getEntityId());
                map.put("post",post);
                commentVOList.add(map);
            }
        }
        model.addAttribute("comments",commentVOList);
        return "/site/my-reply";
    }


}
